import angular from "angular"
import moment from "moment"
import { get, property } from "lodash"

const addOneHtml = require("./addOne.html")

angular.module('rentDetail')
    .service("addOneModal", ["yunkeModal", "$routeParams", function (yunkeModal, $routeParams) {
        return function ({ item, title, params }) {
            return yunkeModal.open({
                controller: "addOneController",
                template: addOneHtml,
                resolve: {
                    contractId: $routeParams.id,
                    item,
                    params
                },
                title
            })
        }
    }])
    .service("modalServer", ["$http", ($http) => {
        return {
            adBalance({ contractId, Id }) {
                return $http.get("/api/index.php?r=contract/ad-balance", {
                    params: {
                        contractId, Id
                    }
                })
            }

        }
    }])
    .directive("ceMin", ["$parse", function () {
        return {
            restrict: 'A',
            require: '?ngModel',
            scope: {
                "ceMin": "="
            },
            link(scope, elm, attr, ctrl) {
                if (!ctrl) return;
                let min = "";
                scope.$watch("ceMin", function (n) {
                    min = +n
                })
                ctrl.$validators.minlength = function (modelValue, viewValue) {
                    return ctrl.$isEmpty(viewValue) || ctrl.$isEmpty(min) || +viewValue <= min;
                };
            }
        };
    }])
    .controller('addOneController', ['$scope', 'item', 'modalInstance', 'modalServer', 'params', function (s, item, modalInstance, modalServer, params) {
        const startOn = get(item, "startOn")
        const endOn = get(item, "endOn")
        const money = get(item, "Money")
        s.startOn = startOn ? moment(+startOn).format("YYYY-MM-DD") : ""
        s.endOn = endOn ? moment(+endOn).format("YYYY-MM-DD") : ""
        s.Money = money;
        modalServer.adBalance(params)
            .then(property("data.data"))
            .then(({ usable }) => {
                s.usable = usable
            })
        s.click = function () {
            const file = s.file
            modalInstance.resolve({
                startOn: s.startOn,
                endOn: s.endOn,
                Money: s.Money,
                "file": file
            })
        }
        s.cancel = function () {
            modalInstance.reject("user cancel")
        }
    }]);
